@file:kotlin.OptIn(ExperimentalFoundationApi::class)

package com.bw.home

import android.annotation.SuppressLint
import android.net.Uri
import android.widget.Switch
import androidx.annotation.OptIn
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.Role.Companion.Switch
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.media3.common.MediaItem
import androidx.media3.common.util.UnstableApi
import androidx.media3.common.util.Util
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DefaultDataSourceFactory
import androidx.media3.exoplayer.SimpleExoPlayer
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.ui.PlayerView
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import com.bw.home.viewmodel.HomeViewModel
import com.bw.lib_common.NavPath
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.w3c.dom.Text

@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(UnstableApi::class)
@Composable
fun HomeDetailsPage(
    navHostController: NavHostController,
    vm: HomeViewModel = hiltViewModel(),
    scope: CoroutineScope = rememberCoroutineScope()
) {
    val entity = vm.getVideoItem()!!

    //实例化exo
    val exoPlayer = remember {
        SimpleExoPlayer.Builder(vm.context).build().apply {
            val dataSourceFactory: DataSource.Factory = DefaultDataSourceFactory(
                vm.context,
                Util.getUserAgent(vm.context, vm.context.packageName)
            )
            val source = ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(
                MediaItem.fromUri(Uri.parse(entity.videopath))
            )

            this.prepare(source)
        }
    }

    val topList = listOf("简介", "评论")

//    var selected by remember {
//        mutableStateOf(0)
//    }

    val pageState = rememberPagerState {
        topList.size
    }

    Column(
        Modifier
            .fillMaxWidth()
            .fillMaxHeight()
    ) {
        LaunchedEffect(key1 = "") {
            //初始播放状态
//        exoPlayer.play()
            exoPlayer.stop()
        }

        AndroidView(
            factory = { context ->
                PlayerView(context).apply {
                    player = exoPlayer
                }
            },
            Modifier
                .height(200.dp)
                .fillMaxWidth()
        )

        Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {

            ScrollableTabRow(
                selectedTabIndex = pageState.currentPage,
                modifier = Modifier.weight(1f)
            ) {
                topList.forEachIndexed { index, title ->
                    Tab(selected = pageState.currentPage == index,
                        onClick = {
                            scope.launch {
                                pageState.scrollToPage(index)
                            }
                        },
                        text = {
                            Text(text = "${title}")
                        }
                    )
                }
            }

            Text(text = "弹幕")

            MyScreen()
        }
        HorizontalPager(state = pageState) {
            when (pageState.currentPage) {
                0 -> {
                    ProfilePage(entity = entity)
                }

                1 -> {
                    CommendPage(entity = entity)
                }

                else -> {}
            }
        }
    }
}

@Composable
fun CustomSwitch(
    isChecked: Boolean,
    onCheckedChanged: (Boolean) -> Unit
) {
    val context = LocalContext.current
    val switch = remember { mutableStateOf(isChecked) }

    Box(
        modifier = Modifier.size(56.dp, 32.dp), // 根据需要调整大小
        contentAlignment = Alignment.Center
    ) {
        AndroidView(
            factory = { context ->
                Switch(context).apply {
//                    isChecked = switch.value
                    setOnCheckedChangeListener { _, isChecked ->
                        switch.value = isChecked
                        onCheckedChanged(isChecked)
                    }
                }
            },
            update = { switchView ->
                if (switchView is Switch) {
                    switchView.isChecked = switch.value
                }
            }
        )
    }
}

// 使用方式
@Composable
fun MyScreen() {
    var isSwitchOn by remember { mutableStateOf(false) }

    CustomSwitch(
        isChecked = isSwitchOn,
        onCheckedChanged = { isSwitchOn = it }
    )
}